package com.falling.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.falling.reggie.common.R;
import com.falling.reggie.entity.Category;
import com.falling.reggie.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        if(categoryService.save(category)) return R.success("save success...");
        else return R.error("save fail...");
    }

    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize){
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getUpdateTime);

        categoryService.page(pageInfo, queryWrapper);

        if (pageInfo.getTotal() == 0) return R.error("no field");
        else return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> delete(Long ids){
        if (categoryService.remove(ids)) return R.success("delete success...");
        else return R.error("delete fail...");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        if(categoryService.updateById(category)) return R.success("update success...");
        else return R.error("update fail...");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> categories = categoryService.list(queryWrapper);
        if (categories != null) return R.success(categories);
        else return R.error("query list fail...");
    }

}
